/**
 * Copyright 2018 jianggujin (www.jianggujin.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jianggujin.modulelink.mvc.util;

import java.util.Collections;
import java.util.Enumeration;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import com.jianggujin.modulelink.util.JAssert;

/**
 * 请求对象封装
 * 
 * @author jianggujin
 *
 */
public class JHttpServletRequestWrapper extends HttpServletRequestWrapper {

    private volatile Map<String, ?> paraMap = null;

    public JHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
    }

    @SuppressWarnings("unchecked")
    private void ensureParseParameter() {
        if (this.paraMap == null) {
            synchronized (this) {
                if (this.paraMap == null) {
                    this.paraMap = super.getRequest().getParameterMap();
                }
            }
        }
    }

    @Override
    public ServletRequest getRequest() {
        return this;
    }

    @Override
    public String getParameter(String name) {
        ensureParseParameter();
        return JWebUtils.getFirstParam(this.paraMap.get(name));// request.getParameter(name);
    }

    @Override
    public Enumeration<String> getParameterNames() {
        ensureParseParameter();
        return Collections.enumeration(this.paraMap.keySet()); // request.getParameterNames();
    }

    @Override
    public String[] getParameterValues(String name) {
        ensureParseParameter();
        return JWebUtils.getParams(this.paraMap.get(name));// request.getParameterValues(name);
    }

    @Override
    public Map<String, ?> getParameterMap() {
        ensureParseParameter();
        return this.paraMap;// request.getParameterMap();
    }

    public void setParameterMap(Map<String, ?> paraMap) {
        JAssert.checkNotNull(paraMap, "paraMap must not be null.");
        this.paraMap = paraMap;
    }
}
